import React, { useEffect } from 'react'
import useGetTableData from '@/hooks/useGetTableDataV2'
import SearchForm from '@/components/QsfCustomForm/SearchForm'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useSupplierColumns } from '../TableColumns'
import { PurchaseFabricOrderVO as ITableData } from '../types'
import CustomTable from '@/components/QsfCustomTable'
import { searchConfigOfSupplier } from '../FormConfig'
import useSearchSupplier from '@/hooks/useSearchSupplier'
import '../index.less'
import useCachePage from '@/hooks/useCachePage'
import { getPurchaseSupplierFabricStock } from '@/api/fabric'
const Index: React.FC = () => {
  const [form] = useForm()
  const { SupplierOption, setSupplierOption, handleSearchSupplier } = useSearchSupplier('supplierCode')
  const { setCachePage, getCachePage } = useCachePage()
  const { tableProps, params, search, reset, reload } = useGetTableData<ITableData>(getPurchaseSupplierFabricStock, {
    form: form,
    immediatelySend: false,
    cachePageCallback: (current, size, prevSize) => {
      const cacheData = getCachePage()
      setCachePage({
        ...cacheData,
        current: prevSize === size ? current : 1,
        size,
      })
    },
  })
  useEffect(() => {
    handleCacheData()
  }, [])
  const handleCacheData = async () => {
    const cacheData = getCachePage()
    if (cacheData == null) {
      await form.validateFields()
      search()
      setCachePage({ ...params })
    } else {
      const { SupplierOption, ...resetCacheData } = cacheData
      // 先重置表单再设置缓存！！！
      form.resetFields()
      form.setFieldsValue({
        ...resetCacheData,
      })
      setSupplierOption(SupplierOption || [])
      reload({ ...resetCacheData })
    }
  }
  return (
    <PageContainer className="fabric_stock_wrap">
      <SearchForm
        className="StockOfSupplier"
        loading={tableProps.loading}
        form={form}
        searchConfig={searchConfigOfSupplier({
          SupplierOption,
          handleSearchSupplier,
        })}
        onFinish={async () => {
          setCachePage({
            ...form.getFieldsValue(),
            SupplierOption,
            current: 1,
            size: params.size,
          })
          search()
        }}
        onReset={() => {
          reset()
          setCachePage({
            current: 1,
            size: 10,
          })
        }}
      ></SearchForm>
      <CustomTable
        stripe={false}
        isAutoScrollY
        {...tableProps}
        columns={useSupplierColumns()}
        rowKey={(rows) =>
          (rows?.supplierCode || '') +
          (rows?.useSite || '') +
          (rows?.fabricName || '') +
          (rows?.fabricColorDetailName || '')
        }
        searchFormClassName="StockOfSupplier"
        extraHeight={36}
      ></CustomTable>
    </PageContainer>
  )
}

export default Index
